<?php
if (!defined('ABSPATH')) { exit; }

function scf_meihua_divination_shortcode($atts = []) {
    // 参数：seed、moment、autocalc、show_form（已存在）
    // 新增参数：
    // - show_intro, show_duanyu, show_suggestion, show_mutual, show_changed, show_lines
    // - theme（default/compact），history（true/false）
    $atts = shortcode_atts([
        'seed'         => '',
        'moment'       => '',
        'autocalc'     => 'false',
        'show_form'    => 'true',
        'show_intro'   => 'true',
        'show_duanyu'  => 'true',
        'show_suggestion' => 'true',
        'show_mutual'  => 'true',
        'show_changed' => 'true',
        'show_lines'   => 'true',
        'theme'        => 'default',
        'history'      => 'false',
    ], $atts, 'meihua_divination');

    // 统一布尔参数解析
    $to_bool = function($v) {
        $v = strtolower(trim((string)$v));
        return !in_array($v, ['0','false','no','off','']);
    };

    $autocalc      = $to_bool($atts['autocalc']);
    $show_form     = $to_bool($atts['show_form']);
    $show_intro    = $to_bool($atts['show_intro']);
    $show_duanyu   = $to_bool($atts['show_duanyu']);
    $show_suggestion = $to_bool($atts['show_suggestion']);
    $show_mutual   = $to_bool($atts['show_mutual']);
    $show_changed  = $to_bool($atts['show_changed']);
    $show_lines    = $to_bool($atts['show_lines']);
    $theme         = sanitize_text_field($atts['theme']);
    $history_on    = $to_bool($atts['history']);

    // 安全
    $seed = isset($_POST['scf_meihua_seed']) ? sanitize_text_field($_POST['scf_meihua_seed']) : sanitize_text_field($atts['seed']);
    $moment = isset($_POST['scf_meihua_moment']) ? sanitize_text_field($_POST['scf_meihua_moment']) : sanitize_text_field($atts['moment']);

    // 如果请求提交则覆盖 autocalc
    $submitted = isset($_POST['scf_meihua_submit']);
    if ($submitted) {
        if (!isset($_POST['scf_meihua_nonce']) || !wp_verify_nonce($_POST['scf_meihua_nonce'], 'scf_meihua_action')) {
            return '<div class="scf-error">安全校验失败，请刷新后重试。</div>';
        }
        $autocalc = true;
    }

    // 计算模型：更贴近梅花易数（时间数、象数、动爻）
    $result_html = '';
    $model = null;
    $details = null;

    if ($autocalc) {
        $moment_used = $moment ? $moment : date_i18n('Y-m-d H:i');
        $model = scf_meihua_compute_model($seed, $moment_used);
        $names = scf_hexagram_names();
        $details_all = scf_hexagram_details();

        // 原卦
        $orig_num = $model['hex_num'];
        $orig_name = isset($names[$orig_num]) ? $names[$orig_num] : ('第' . $orig_num . '卦');
        $orig_detail = isset($details_all[$orig_num]) ? $details_all[$orig_num] : null;

        // 互卦/变卦
        $mutual_num = $model['mutual_num'];
        $mutual_name = isset($names[$mutual_num]) ? $names[$mutual_num] : ('第' . $mutual_num . '卦');
        $mutual_detail = isset($details_all[$mutual_num]) ? $details_all[$mutual_num] : null;

        $changed_num = $model['changed_num'];
        $changed_name = isset($names[$changed_num]) ? $names[$changed_num] : ('第' . $changed_num . '卦');
        $changed_detail = isset($details_all[$changed_num]) ? $details_all[$changed_num] : null;

        // 动爻提示
        $moving = (int)$model['moving_line']; // 1..6（自下而上计数）
        $lines = $model['lines']; // 顶->底 6 位，1/0（阳/阴）
        $idx_top = 6 - $moving; // 顶->底索引
        $is_yang = isset($lines[$idx_top]) ? (int)$lines[$idx_top] === 1 : null;
        $moving_text = '动爻：第' . $moving . '爻（' . ($is_yang ? '阳' : '阴') . '）';

        // 构建结果 HTML
        $container_class = 'scf-card scf-meihua' . ($theme === 'compact' ? ' scf-meihua--compact' : '');
        $result_html .= '<div class="' . esc_attr($container_class) . '">';
        $result_html .= '<h3 class="scf-title">梅花易数断卦</h3>';
        $result_html .= '<div class="scf-meihua-summary">';
        $result_html .= '<div><strong>原卦：</strong>' . esc_html($orig_name) . '（序号 ' . esc_html($orig_num) . '）</div>';
        if ($show_lines) {
            $result_html .= '<div><strong>' . esc_html($moving_text) . '</strong></div>';
        }
        $result_html .= '</div>';

        if ($show_intro && $orig_detail && isset($orig_detail['intro'])) {
            $result_html .= '<div class="scf-meihua-block"><strong>卦意：</strong>' . esc_html($orig_detail['intro']) . '</div>';
        }
        if ($show_duanyu && $orig_detail && isset($orig_detail['duanyu'])) {
            $result_html .= '<div class="scf-meihua-block"><strong>断语：</strong>' . esc_html($orig_detail['duanyu']) . '</div>';
        }
        if ($show_suggestion && $orig_detail && isset($orig_detail['suggestion'])) {
            $result_html .= '<div class="scf-meihua-block"><strong>建议：</strong>' . esc_html($orig_detail['suggestion']) . '</div>';
        }

        if ($show_mutual) {
            $result_html .= '<hr /><div class="scf-meihua-block"><strong>互卦：</strong>' . esc_html($mutual_name) . '（序号 ' . esc_html($mutual_num) . '）</div>';
            if ($mutual_detail && isset($mutual_detail['intro'])) {
                $result_html .= '<div class="scf-meihua-sub">' . esc_html($mutual_detail['intro']) . '</div>';
            }
            if ($show_duanyu && $mutual_detail && isset($mutual_detail['duanyu'])) {
                $result_html .= '<div class="scf-meihua-sub">' . esc_html($mutual_detail['duanyu']) . '</div>';
            }
        }

        if ($show_changed) {
            $result_html .= '<hr /><div class="scf-meihua-block"><strong>变卦：</strong>' . esc_html($changed_name) . '（序号 ' . esc_html($changed_num) . '）</div>';
            if ($changed_detail && isset($changed_detail['intro'])) {
                $result_html .= '<div class="scf-meihua-sub">' . esc_html($changed_detail['intro']) . '</div>';
            }
            if ($show_duanyu && $changed_detail && isset($changed_detail['duanyu'])) {
                $result_html .= '<div class="scf-meihua-sub">' . esc_html($changed_detail['duanyu']) . '</div>';
            }
        }

        // 历史记录
        if ($history_on) {
            $entry = [
                'time' => current_time('mysql'),
                'seed' => $seed,
                'moment' => $moment_used,
                'orig' => $orig_num,
                'mutual' => $mutual_num,
                'changed' => $changed_num,
                'moving' => $moving,
            ];
            $hist = get_option('scf_meihua_history', []);
            if (!is_array($hist)) { $hist = []; }
            $hist[] = $entry;
            if (count($hist) > 20) { $hist = array_slice($hist, -20); }
            update_option('scf_meihua_history', $hist);

            $result_html .= '<hr /><div class="scf-meihua-block"><strong>最近记录：</strong>';
            $recent = array_slice($hist, -5);
            if (!empty($recent)) {
                $result_html .= '<ul class="scf-meihua-history">';
                foreach ($recent as $item) {
                    $result_html .= '<li>' . esc_html($item['time']) . ' | 种子：' . esc_html($item['seed']) . ' | 原卦：' . esc_html($item['orig']) . ' → 变卦：' . esc_html($item['changed']) . '</li>';
                }
                $result_html .= '</ul>';
            } else {
                $result_html .= '暂无记录。';
            }
            $result_html .= '</div>';
        }

        $result_html .= '</div>'; // /scf-card
    }

    // 表单
    $html = '';
    if ($show_form) {
        $html .= '<form method="post" class="scf-form scf-meihua-form">';
        $html .= wp_nonce_field('scf_meihua_action', 'scf_meihua_nonce', true, false);
        $html .= '<div class="scf-field"><label>种子（问事人/主题词）：</label><input type="text" name="scf_meihua_seed" value="' . esc_attr($seed) . '" placeholder="如：合作项目或某人姓名" /></div>';
        $html .= '<div class="scf-field"><label>时刻（空则取当前）：</label><input type="text" name="scf_meihua_moment" value="' . esc_attr($moment) . '" placeholder="YYYY-MM-DD HH:MM" /></div>';
        $html .= '<div class="scf-actions"><button type="submit" class="button button-primary" name="scf_meihua_submit" value="1">起卦并断</button></div>';
        $html .= '</form>';
    }

    return $html . $result_html;
}

function scf_hexagram_names() {
    // 64卦名，序号从1开始
    return [
        1 => '乾为天', 2 => '坤为地', 3 => '水雷屯', 4 => '山水蒙', 5 => '水天需', 6 => '天水讼', 7 => '地水师', 8 => '水地比',
        9 => '风天小畜', 10 => '天泽履', 11 => '地天泰', 12 => '天地否', 13 => '天火同人', 14 => '火天大有', 15 => '地山谦', 16 => '雷地豫',
        17 => '泽雷随', 18 => '山风蛊', 19 => '地泽临', 20 => '风地观', 21 => '火雷噬嗑', 22 => '山火贲', 23 => '山地剥', 24 => '地雷复',
        25 => '天雷无妄', 26 => '山天大畜', 27 => '山雷颐', 28 => '泽风大过', 29 => '坎为水', 30 => '离为火', 31 => '泽山咸', 32 => '雷风恒',
        33 => '天山遁', 34 => '雷天大壮', 35 => '火地晋', 36 => '地火明夷', 37 => '风火家人', 38 => '火泽睽', 39 => '水山蹇', 40 => '雷水解',
        41 => '山泽损', 42 => '风雷益', 43 => '泽天夬', 44 => '天风姤', 45 => '泽地萃', 46 => '地风升', 47 => '泽水困', 48 => '水风井',
        49 => '泽火革', 50 => '火风鼎', 51 => '震为雷', 52 => '艮为山', 53 => '风山渐', 54 => '雷泽归妹', 55 => '雷火丰', 56 => '火山旅',
        57 => '巽为风', 58 => '兑为泽', 59 => '风水涣', 60 => '水泽节', 61 => '风泽中孚', 62 => '雷山小过', 63 => '水火既济', 64 => '火水未济'
    ];
}

// 增补：64卦简明断语（演示版）
function scf_hexagram_details() {
    return [
        1 => ['intro' => '刚健自强，宜进取。', 'duanyu' => '天行健，自强不息。', 'suggestion' => '把握主导，谦虚为要。'],
        2 => ['intro' => '厚德载物，稳中求进。', 'duanyu' => '地势坤，厚德载物。', 'suggestion' => '以柔制刚，耐心等待。'],
        3 => ['intro' => '初始艰难，积蓄以行。', 'duanyu' => '屯难生，慎行可成。', 'suggestion' => '稳步推进，资源先行。'],
        4 => ['intro' => '蒙昧启蒙，教化而进。', 'duanyu' => '启蒙立志，循序渐进。', 'suggestion' => '请教明师，明辨是非。'],
        5 => ['intro' => '需待时机，蓄势而发。', 'duanyu' => '需以待时，动宜审慎。', 'suggestion' => '不急于求成，择机而动。'],
        6 => ['intro' => '争讼纷扰，宜和解。', 'duanyu' => '讼有损，和为贵。', 'suggestion' => '以理服人，避强争锋。'],
        7 => ['intro' => '整肃队伍，纪律为先。', 'duanyu' => '师出有名，令行禁止。', 'suggestion' => '统一目标，强组织力。'],
        8 => ['intro' => '亲比合众，凝聚人心。', 'duanyu' => '比而同心，众志成城。', 'suggestion' => '加强协作，增信互助。'],
        9 => ['intro' => '小有积蓄，稳健养成。', 'duanyu' => '小畜不躁，积少成多。', 'suggestion' => '坚持节制，耐心等待。'],
        10 => ['intro' => '履道安稳，谨慎行事。', 'duanyu' => '履之以慎，踏实前进。', 'suggestion' => '按部就班，守礼而行。'],
        11 => ['intro' => '泰则通达，上下和谐。', 'duanyu' => '泰则大通，吉祥安泰。', 'suggestion' => '乘势而上，不忘基础。'],
        12 => ['intro' => '否塞不通，宜守待机。', 'duanyu' => '否极生通，暂避锋芒。', 'suggestion' => '修内功，少冒进。'],
        13 => ['intro' => '同人协力，共谋大业。', 'duanyu' => '同人于野，心齐事成。', 'suggestion' => '广结善缘，开放合作。'],
        14 => ['intro' => '大有收获，善用资源。', 'duanyu' => '大有可为，丰而不骄。', 'suggestion' => '分享收益，防止自满。'],
        15 => ['intro' => '谦逊自守，德行增长。', 'duanyu' => '谦以自抑，德不孤。', 'suggestion' => '低调务实，礼让为佳。'],
        16 => ['intro' => '喜乐鼓舞，预示向好。', 'duanyu' => '豫而不逸，乐以有节。', 'suggestion' => '振奋团队，防止松懈。'],
        17 => ['intro' => '随势而动，顺应变化。', 'duanyu' => '随而有则，顺势成事。', 'suggestion' => '不失原则，灵活调整。'],
        18 => ['intro' => '修旧治弊，革故鼎新。', 'duanyu' => '蛊有病，治之可安。', 'suggestion' => '查缺补漏，整顿提升。'],
        19 => ['intro' => '临事得机，近而有利。', 'duanyu' => '临之以敬，机遇可期。', 'suggestion' => '主动接近，慎重把握。'],
        20 => ['intro' => '观摩省察，自我反思。', 'duanyu' => '观其所行，明其得失。', 'suggestion' => '多观察，少干预。'],
        21 => ['intro' => '刚柔并济，啮合解决。', 'duanyu' => '噬嗑破坚，行之有力。', 'suggestion' => '果断执行，依法推进。'],
        22 => ['intro' => '文饰其表，内外相辅。', 'duanyu' => '贲而不伪，美以诚心。', 'suggestion' => '重品牌与内涵兼修。'],
        23 => ['intro' => '剥落减损，谨防风险。', 'duanyu' => '剥极重整，守拙避祸。', 'suggestion' => '收缩防守，保存实力。'],
        24 => ['intro' => '旧去新来，循环复始。', 'duanyu' => '复归正道，阳气初生。', 'suggestion' => '从头来过，稳步重建。'],
        25 => ['intro' => '无妄之福，贵在诚正。', 'duanyu' => '无妄则吉，心正事顺。', 'suggestion' => '不妄为，守信守法。'],
        26 => ['intro' => '大畜蓄德，厚积薄发。', 'duanyu' => '畜而有度，时来可用。', 'suggestion' => '储备力量，等待良机。'],
        27 => ['intro' => '颐养正心，饮食有节。', 'duanyu' => '颐以养德，慎言慎行。', 'suggestion' => '修身养性，节制口欲。'],
        28 => ['intro' => '过犹不及，负重之象。', 'duanyu' => '大失误衡，纠偏为先。', 'suggestion' => '分担压力，校正目标。'],
        29 => ['intro' => '险中求安，谨慎行旅。', 'duanyu' => '坎陷之险，守正可安。', 'suggestion' => '保守策略，防范风险。'],
        30 => ['intro' => '光明向上，依附文明。', 'duanyu' => '离明照世，依附成事。', 'suggestion' => '靠拢资源，增强曝光。'],
        31 => ['intro' => '感而相应，互相吸引。', 'duanyu' => '咸则感通，情志相谐。', 'suggestion' => '注重沟通，以诚动人。'],
        32 => ['intro' => '恒久不变，持之以恒。', 'duanyu' => '恒以守常，长久之计。', 'suggestion' => '坚持正道，稳中推进。'],
        33 => ['intro' => '退避以保，伺机再进。', 'duanyu' => '遁而不乱，远祸近福。', 'suggestion' => '战略撤退，保全实力。'],
        34 => ['intro' => '壮而有节，动而可为。', 'duanyu' => '大壮有力，先制后进。', 'suggestion' => '把握节奏，勿蛮进。'],
        35 => ['intro' => '晋升进取，步步高升。', 'duanyu' => '晋之向上，光明可见。', 'suggestion' => '积累口碑，稳步加码。'],
        36 => ['intro' => '明被覆暗，暂避其锋。', 'duanyu' => '明夷受伤，韬光养晦。', 'suggestion' => '低调隐忍，待机而动。'],
        37 => ['intro' => '家道人伦，各司其位。', 'duanyu' => '家人有序，亲和为本。', 'suggestion' => '重视家庭/团队秩序。'],
        38 => ['intro' => '睽违不合，各守其是。', 'duanyu' => '睽而有别，求同存异。', 'suggestion' => '达成共识，减少对立。'],
        39 => ['intro' => '蹇难阻滞，宜缓不宜急。', 'duanyu' => '蹇而多碍，通以德行。', 'suggestion' => '迂回前进，修复关系。'],
        40 => ['intro' => '解困去结，畅通有望。', 'duanyu' => '解所得结，轻装前行。', 'suggestion' => '先排障碍，再谋发展。'],
        41 => ['intro' => '损有余补不足，优化结构。', 'duanyu' => '损中有益，合理取舍。', 'suggestion' => '瘦身提效，聚焦核心。'],
        42 => ['intro' => '益助增益，资源流入。', 'duanyu' => '益而不滥，利在共赢。', 'suggestion' => '引入外援，共享价值。'],
        43 => ['intro' => '决断果敢，斩断犹疑。', 'duanyu' => '夬则决行，快刀斩乱麻。', 'suggestion' => '坚决执行，控制风险。'],
        44 => ['intro' => '突遇其来，防微杜渐。', 'duanyu' => '姤遇无常，谨慎为要。', 'suggestion' => '识别异动，早做防护。'],
        45 => ['intro' => '萃聚合力，汇集人气。', 'duanyu' => '萃而有章，众力所归。', 'suggestion' => '组织活动，增强凝聚。'],
        46 => ['intro' => '由下而上，步步高升。', 'duanyu' => '升以循序，稳步向上。', 'suggestion' => '坚韧不拔，抓住时机。'],
        47 => ['intro' => '困顿受阻，守正待援。', 'duanyu' => '困中求通，于困见志。', 'suggestion' => '求助外援，保守推进。'],
        48 => ['intro' => '汲取之源，基础工程。', 'duanyu' => '井养万物，清源自来。', 'suggestion' => '打好底层，长期运营。'],
        49 => ['intro' => '革故鼎新，变革在即。', 'duanyu' => '革而纳新，趁势而为。', 'suggestion' => '制定路线，稳妥推进。'],
        50 => ['intro' => '鼎立三足，资源整合。', 'duanyu' => '鼎以成事，协作共赢。', 'suggestion' => '搭建架构，联合发力。'],
        51 => ['intro' => '震动惊雷，唤醒变革。', 'duanyu' => '震而有警，迅速应变。', 'suggestion' => '快速响应，稳定人心。'],
        52 => ['intro' => '止于内守，静以制动。', 'duanyu' => '艮之止，动静相宜。', 'suggestion' => '先稳后动，修身养性。'],
        53 => ['intro' => '循序渐进，缓而有成。', 'duanyu' => '渐之有序，步步为营。', 'suggestion' => '长期主义，小步快跑。'],
        54 => ['intro' => '归妹从嫁，关系调整。', 'duanyu' => '归妹有变，审时度势。', 'suggestion' => '处理关系，慎重承诺。'],
        55 => ['intro' => '丰盛盛大，高峰之象。', 'duanyu' => '丰而不盈，张弛有度。', 'suggestion' => '高峰期防过载。'],
        56 => ['intro' => '旅途在外，独立自持。', 'duanyu' => '旅而居异，守正自安。', 'suggestion' => '保持节制，注意安全。'],
        57 => ['intro' => '巽入风行，渗透扩散。', 'duanyu' => '巽以入人，润物无声。', 'suggestion' => '潜移默化，柔性推进。'],
        58 => ['intro' => '兑悦相说，以利交流。', 'duanyu' => '兑以悦人，沟通顺畅。', 'suggestion' => '提升表达，促成合作。'],
        59 => ['intro' => '涣散散开，重聚信心。', 'duanyu' => '涣而复聚，信为根本。', 'suggestion' => '凝心聚力，化解分歧。'],
        60 => ['intro' => '节制有度，法度自立。', 'duanyu' => '节而有度，约束致远。', 'suggestion' => '制定规则，严格执行。'],
        61 => ['intro' => '中孚诚信，内外相应。', 'duanyu' => '诚信为本，感通人心。', 'suggestion' => '推行信任，稳固关系。'],
        62 => ['intro' => '小过适度，谨慎拿捏。', 'duanyu' => '小过无伤，把握分寸。', 'suggestion' => '不求全责备，趋稳避险。'],
        63 => ['intro' => '既济完成，谨慎守成。', 'duanyu' => '成而不骄，慎终如始。', 'suggestion' => '复盘巩固，防微杜渐。'],
        64 => ['intro' => '未济未成，临门一脚。', 'duanyu' => '事未竟，仍需努力。', 'suggestion' => '补齐短板，收官冲刺。'],
    ];
}

function scf_meihua_pair_index_map() {
    // 通过名称表解析出「上卦/下卦 → 序号」映射，避免手写 64 项
    $names = scf_hexagram_names();
    $map_char_to_id = [
        '乾' => 7, '天' => 7,
        '兑' => 6, '泽' => 6,
        '离' => 5, '火' => 5,
        '震' => 4, '雷' => 4,
        '巽' => 3, '风' => 3,
        '坎' => 2, '水' => 2,
        '艮' => 1, '山' => 1,
        '坤' => 0, '地' => 0,
    ];
    $pair_map = [];
    foreach ($names as $idx => $n) {
        $idx = (int)$idx; if ($idx < 1) continue;
        $u = null; $l = null;
        $n = preg_replace('/\s+/', '', $n);
        if (strpos($n, '为') !== false) {
            // 例：乾为天、坎为水（正则按 UTF-8 单字抓取）
            if (preg_match('/^(.).*为(.)/u', $n, $m)) {
                $u_char = $m[1];
                $l_char = $m[2];
                $u = isset($map_char_to_id[$u_char]) ? $map_char_to_id[$u_char] : null;
                $l = isset($map_char_to_id[$l_char]) ? $map_char_to_id[$l_char] : null;
            }
        } else {
            // 例：水雷屯、山水蒙、风天小畜（抓前两个单字）
            if (preg_match('/^(.)(.)/u', $n, $m)) {
                $u_char = $m[1];
                $l_char = $m[2];
                $u = isset($map_char_to_id[$u_char]) ? $map_char_to_id[$u_char] : null;
                $l = isset($map_char_to_id[$l_char]) ? $map_char_to_id[$l_char] : null;
            }
        }
        if ($u === null || $l === null) { continue; }
        $pair_map[$u . '-' . $l] = $idx;
    }
    return $pair_map;
}

function scf_meihua_pair_to_index($upper_id, $lower_id, $pair_map) {
    $key = ((int)$upper_id) . '-' . ((int)$lower_id);
    if (isset($pair_map[$key])) return (int)$pair_map[$key];
    // 回退：若名称解析失败，使用近似序号（非文王序，仅兜底）
    $u = (int)$upper_id; $l = (int)$lower_id;
    if ($u < 0) $u = 0; if ($u > 7) $u = 7;
    if ($l < 0) $l = 0; if ($l > 7) $l = 7;
    return ($u * 8 + $l) + 1; // 1..64
}

function scf_meihua_trigram_id_to_lines($id) {
    // 顶->底（1 为阳，0 为阴）
    switch ((int)$id) {
        case 7: /* 乾 ☰ */ return [1,1,1];
        case 6: /* 兑 ☱ */ return [1,1,0];
        case 5: /* 离 ☲ */ return [1,0,1];
        case 4: /* 震 ☳ */ return [1,0,0];
        case 3: /* 巽 ☴ */ return [0,1,1];
        case 2: /* 坎 ☵ */ return [0,1,0];
        case 1: /* 艮 ☶ */ return [0,0,1];
        default: /* 坤 ☷ */ return [0,0,0];
    }
}

function scf_meihua_lines_to_trigram_id($lines) {
    $key = implode('', array_map(function($v){return $v?1:0;}, $lines));
    switch ($key) {
        case '111': return 7; // 乾
        case '110': return 6; // 兑
        case '101': return 5; // 离
        case '100': return 4; // 震
        case '011': return 3; // 巽
        case '010': return 2; // 坎
        case '001': return 1; // 艮
        default: return 0; // 坤
    }
}

function scf_meihua_compute_model($seed, $moment) {
    // 基础数：时间（YmdHi）与种子字节和
    $ts = strtotime($moment) ?: time();
    $base_str = date('YmdHi', $ts);
    $time_sum = 0; for ($i=0; $i<strlen($base_str); $i++) { $time_sum += (int)$base_str[$i]; }
    $seed_str = (string)$seed;
    $seed_sum = 0; for ($i=0; $i<strlen($seed_str); $i++) { $seed_sum += ord($seed_str[$i]); }

    $mix = $time_sum + $seed_sum;
    $upper_id = $mix % 8; // 上卦
    $lower_id = ($mix + strlen($seed_str)) % 8; // 下卦

    // 动爻：1..6（自下而上计数）
    $moving = ($mix % 6) + 1;

    // 由上下卦生成 6 爻（顶->底）
    $upper_lines = scf_meihua_trigram_id_to_lines($upper_id); // 3 位 顶->底
    $lower_lines = scf_meihua_trigram_id_to_lines($lower_id); // 3 位 顶->底
    $lines = array_merge($upper_lines, $lower_lines); // 6 位 顶->底

    // 原卦编号（文王序）
    $pair_map = scf_meihua_pair_index_map();
    $hex_num = scf_meihua_pair_to_index($upper_id, $lower_id, $pair_map);

    // 互卦：取原卦第2-4为下卦、第3-5为上卦（顶->底索引 1..3 / 2..4）
    $mut_lower_lines = [$lines[1], $lines[2], $lines[3]];
    $mut_upper_lines = [$lines[2], $lines[3], $lines[4]];
    $mut_lower_id = scf_meihua_lines_to_trigram_id($mut_lower_lines);
    $mut_upper_id = scf_meihua_lines_to_trigram_id($mut_upper_lines);
    $mutual_num = scf_meihua_pair_to_index($mut_upper_id, $mut_lower_id, $pair_map);

    // 变卦：动爻翻转
    $idx_top = 6 - $moving; // 顶->底索引
    $lines_changed = $lines;
    $lines_changed[$idx_top] = $lines_changed[$idx_top] ? 0 : 1;
    $chg_upper_id = scf_meihua_lines_to_trigram_id([$lines_changed[0], $lines_changed[1], $lines_changed[2]]);
    $chg_lower_id = scf_meihua_lines_to_trigram_id([$lines_changed[3], $lines_changed[4], $lines_changed[5]]);
    $changed_num = scf_meihua_pair_to_index($chg_upper_id, $chg_lower_id, $pair_map);

    return [
        'upper_id'   => $upper_id,
        'lower_id'   => $lower_id,
        'hex_num'    => $hex_num,
        'lines'      => $lines,
        'moving_line'=> $moving,
        'mutual_num' => $mutual_num,
        'changed_num'=> $changed_num,
    ];
}